package failover

import (
	"context"
	"errors"
	"jk-time/webook/internal/service/sms"
	"sync/atomic"
)

type FailoverSMSService struct {
	svcs []sms.Service
	idx  int32
}

func NewFailoverSMSService(svcs []sms.Service) sms.Service {
	return &FailoverSMSService{
		svcs: svcs,
		idx:  0,
	}
}
func (f FailoverSMSService) Send(ctx context.Context, tplId string, args []string, numbers ...string) error {
	for _, svc := range f.svcs {
		err := svc.Send(ctx, tplId, args, numbers...)
		if err == nil {
			return nil
		}
	}
	return errors.New("发送失败，所有服务商都尝试过了")
}
func (f FailoverSMSService) SendV1(ctx context.Context, tplId string, args []string, numbers ...string) error {
	idx := atomic.AddInt32(&f.idx, 1)
	length := int32(len(f.svcs))
	for i := idx; i < idx+length; i++ {
		svc := f.svcs[i%length]
		err := svc.Send(ctx, tplId, args, numbers...)
		switch err {
		case nil:
			return nil
		case context.DeadlineExceeded, context.Canceled:
			//超时时间到，主动取消
			return err
		}
	}
	return errors.New("发送失败，所有服务商都尝试过了")
}
